package com.atguigu.day03;

import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @description :
 * @autor :lyh
 */
public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
                .fromElements(1, 2, 3, 4, 5, 6, 7, 8)
                .setParallelism(1)
                .partitionCustom(
                        // key 是 integer 类型
                        // 指定某个 key 的数据要发送到哪一个索引到的并行子任务
                        new Partitioner<Integer>() {
                            @Override
                            public int partition(Integer key, int numPartitions) {
                                if (key == 0 || key == 1) {
                                    return 0; // 将 key 为 0 或者 1的数据发送到print索引为0的并行子任务
                                } else {
                                    return 1;
                                }
                            }
                        },
                        new KeySelector<Integer, Integer>() {
                            @Override
                            public Integer getKey(Integer in) throws Exception {
                                return in % 3; // 将输入的数据除以3的余数指定为key
                            }
                        }
                )
                .print()
                .setParallelism(4);

        env.execute();
    }
}
